package cc.linker.steplink.crm.commons.service;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.domain.ConfigXmlDto;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置中心接口调用
 */
@Service
@Slf4j
public class UserCenterService {

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private HttpService httpService;

    private final static String PROPERTIES_PREFIX = "StepLink_";

    /**
     * <p>根据键名获取配置中心配置的路径</p>
     * <p>尝试从内存中读取</p>
     *
     * @param keyCode
     * @param request
     * @return
     */
    public String getSysUrl(String keyCode, HttpServletRequest request) {
        try {
            // 优先内存获取
            String baseUrl = System.getProperty(request.getContextPath() + PROPERTIES_PREFIX + keyCode);
            if (StringUtils.isEmpty(baseUrl)) {
                baseUrl = getUrl(keyCode, request);
            }
            return baseUrl;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("配置中心返回地址出错");
        }
        return null;
    }

    /**
     * <p>根据键名获取配置中心配置的路径</p>
     * <p>获取后会存储到内存中</p>
     *
     * @param keyCode
     * @param request
     * @return
     */
    public String getUrl(String keyCode, HttpServletRequest request) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", ConfigXmlDto.Content_Type);
            headers.put("SOAPAction", ConfigXmlDto.SOAPAction);

            String xml = ConfigXmlDto.msgXml.replace("${config_key}", keyCode);
            LOGGER.info("RequestUrl" + systemProperties.getConfigUrl() + "向配置中心请求业务系统地址：[keyCode]" + keyCode + xml);
            String result = httpService.doPost(systemProperties.getConfigUrl(), xml, headers);
            LOGGER.info("RequestUrl" + systemProperties.getConfigUrl() + "配置中心返回：" + result);

            Document document = DocumentHelper.parseText(result);
            Element ele = document.getRootElement();
            Element body = ele.element("Body");
            Element res = body.element("ConfigQueryResponse").element("ConfigQueryResult");
            String code = res.elementText("ResultCode");
            if ("ProcSuccess".equals(code)) {
                Element obj = res.element("ResultData").element("Config");
                String baseUrl = obj.elementText("KeyValue");
                System.setProperty(request.getContextPath() + PROPERTIES_PREFIX + keyCode, baseUrl);
                return baseUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("请求配置中心出错");
        }
        return null;
    }
}
